﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace P3SS.IPC
{
	/// <summary>
	/// Contains functions to deal with WCF
	/// </summary>
	public static class Connector
	{
		private const string ENDPOINT_ADDRESS = "net.pipe://localhost/p3ss/service";

		/// <summary>
		/// Creates and establishes a host endpoint
		/// </summary>
		public static void HostService(IP3SSService inService)
		{
			NetNamedPipeBinding namedPipe = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
			ServiceHost serviceHost = new ServiceHost(inService, new Uri(ENDPOINT_ADDRESS));

			serviceHost.AddServiceEndpoint(typeof(IP3SSService), namedPipe, ENDPOINT_ADDRESS);
			serviceHost.Open();
		}

		/// <summary>
		/// Opens a connection to the service
		/// </summary>
		/// <returns>If open successful, a Channel to the service. Otherwise null</returns>
		public static IServiceChannel OpenService()
		{
			NetNamedPipeBinding namedPipe = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);
			EndpointAddress endpoint = new EndpointAddress(ENDPOINT_ADDRESS);
			IServiceChannel channel = ChannelFactory<IServiceChannel>.CreateChannel(namedPipe, endpoint);

			try
			{
				channel.Open();
			}
			catch
			{
				channel.Dispose();
				channel = null;
			}

			return channel;
		}

		/// <summary>
		/// Closes and disposes of a channel
		/// </summary>
		/// <param name="inChannel">Channel to dispose of</param>
		public static void CloseService(IServiceChannel inChannel)
		{
			try
			{
				inChannel.Close();
			}
			finally
			{
				inChannel.Dispose();
			}
		}
	}
}
